package com.njym.java.security.app.rest;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.njym.java.security.app.annotation.PageView;
import com.njym.java.security.app.biz.CourseCatalogueBiz;
import com.njym.java.security.app.biz.CourseSectionBiz;
import com.njym.java.security.app.biz.FamilyUserBiz;
import com.njym.java.security.app.biz.FamilyWalletRecordBiz;
import com.njym.java.security.app.entity.CourseSection;
import com.njym.java.security.app.entity.FamilyUser;
import com.njym.java.security.app.entity.FamilyWalletRecord;
import com.njym.java.security.app.utils.RedisUtils;
import com.njym.java.security.common.msg.ObjectRestResponse;
import com.njym.java.security.common.rest.BaseController;
import com.njym.java.security.common.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Controller
@RequestMapping("courseSection")
@Slf4j
public class CourseSectionController extends BaseController<CourseSectionBiz, CourseSection> {
    @Autowired
    private CourseCatalogueBiz courseCatalogueBiz;
    @Autowired
    private FamilyUserBiz familyUserBiz;
    @Autowired
    private PlatformTransactionManager txManager;
    @Autowired
    private FamilyWalletRecordBiz familyWalletRecordBiz;

    @Autowired
    private RedisUtils redisUtil;

    private StringRedisTemplate stringRedisTemplate;

    private final Log logger = LogFactory.getLog(FamilyWalletRecordController.class);

    public CourseSectionController(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 查询所有课时
     * @param couId
     * @return
     */
    @RequestMapping(value = "/getAllSectionById", method = RequestMethod.GET)
    @ResponseBody
    public Object getAllSectionById(String couId) {
        if (!couId.equals("undefined")) {
            Example example = new Example(CourseSection.class);
            example.createCriteria().andEqualTo("couId",Integer.parseInt(couId));
            example.orderBy("sectionOrder");
            Map<String,Object> data = new HashMap<>();
            data.put("data",baseBiz.selectByExample(example));
            return new ObjectRestResponse<Object>().rel(true).data(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }
    }

    private List<Integer> couId_list = new ArrayList<>();
    private Map<String, Integer> the_map = new HashMap<>();


    /**
     *添加播放量
     */
    @PageView
    @RequestMapping(value = "/playTimes", method = RequestMethod.GET)
    @ResponseBody
    public Object setPlayTimes(Integer id,Integer userId ){
        //插入缓存，根据课程id，存入缓存数据
//        String  key  = id.toString() + userId.toString()+new Date();
//        stringRedisTemplate.opsForValue().set(key, "hello redis", 1100, TimeUnit.SECONDS);
//        cou_list.add(id);

//        if (!this.the_map.containsKey("map_"+id)) {   //不存在课时id
//            this.the_map.put("map_"+id, 1);
//            this.couId_list.add(id);
//        }else {     //存在
//            Integer o = this.the_map.get("map_" + id);
//            System.out.println(o);
//            this.the_map.put("map_" + id, o + 1);
//            System.out.println(this.the_map.get("map_" + id));
//        }

        try{
            CourseSection cs  =   baseBiz.selectById(id);
            log.info("id = {}", id);
            String key = "id_"+id;
            Long view = redisUtil.size(key);
            log.info("redis 缓存中浏览数：{}", view);
            //直接从缓存中获取并与之前的数量相加
            Long views = view + cs.getPlayTimes();
            log.info("文章总浏览数：{}", views);
            return ResponseUtil.ok();
        } catch (Throwable e) {
            log.info("报错：{}", e);
            return ResponseUtil.fail(-1, "错误！");
        }

    }

    /**
     * 定时任务，每5分钟一次
//     */
//    @Scheduled(cron = "0 */5 * * * ?")
//    @Transactional(rollbackFor = RuntimeException.class)
//    public void updatePlayTimes(){
//        System.out.println(this.the_map);
//        System.out.println(this.couId_list);
//        if (this.couId_list.size() > 0) {
//            this.couId_list.forEach( id ->{
//                Integer times = this.the_map.get("map_"+id);
//                System.out.println(times);
//                baseBiz.updatePlayTimes(id, times);
//            });
//            this.the_map.clear();
//            this.couId_list.clear();
//        }
//
//    }

    @Scheduled(cron = "0 0 1 * * ? ")
    @Transactional(rollbackFor=Exception.class)
    public void createHyperLog() {
        log.info("浏览量入库开始");

        Example example = new Example(CourseSection.class);
        example.createCriteria().andEqualTo("deleted",0);
        Map<String,Object> data = new HashMap<>();

        List<CourseSection> list = baseBiz.selectByExample(example);
        list.forEach(id ->{
            // 获取每一篇文章在redis中的浏览量，存入到数据库中
            String key  = "id_"+id;
            Long view = redisUtil.size(key);
            if(view>0){
                CourseSection cs  =   baseBiz.selectById(id);
                Long views = view + cs.getPlayTimes();
                cs.setPlayTimes(Math.toIntExact(views));
                 baseBiz.updateById(cs);
                 log.info("数据库更新后的浏览量为：{}", views);
                 redisUtil.del(key);
            }
        });
        log.info("浏览量入库结束");
    }




    /**
     * 根据首页传过来的课程名获取音频课时
     * @param flag  是否兑换
     * @param courseId  课程id   金玉良言53   爱听54
     * @return
     */
    @RequestMapping(value = "/getAudios", method = RequestMethod.GET)
    @ResponseBody
    public Object lists(@RequestParam(defaultValue = "10") int limit,
                       @RequestParam(defaultValue = "1") int page,
                       String userId, Integer flag, Integer courseId
//                        String courseName  “金玉良言”课程名暂时不要了，现在只有金玉良言需要兑换了
                        ) {
        if (!userId.equals("undefined")) {
            Map<String,Object> data = new HashMap<>();
//            List<CourseSection> list = new ArrayList<>();
            if(courseId == 53){             //-------------金玉良言--------------------
                Page<CourseSection> result = PageHelper.startPage(page, limit);
                if (flag == 1) {  //已兑换的
                    baseBiz.select_jyly_haveGotten(Integer.parseInt(userId), courseId);
                }else { //未兑换的，可兑换的
                    baseBiz.select_jyly_neverGotten(Integer.parseInt(userId), courseId);
                }
                List<CourseSection> list = result.getResult();
                list.forEach(CourseSection ->{
                    // 获取每一篇文章在redis中的浏览量，存入到数据库中
                    String key  = "id_"+CourseSection.getId();
                    Long view = redisUtil.size(key);
                    if(view>0){
                        Long views = view + CourseSection.getPlayTimes();
                        CourseSection.setPlayTimes(Math.toIntExact(views));
                    }
                });

                data.put("list",list);
                data.put("total",result.getPages());
                return new ObjectRestResponse<Object>().rel(true).data(data);
            }else {             //------------------爱听------------------
                Page<CourseSection> result = PageHelper.startPage(page, limit);
                baseBiz.select_AiTing(courseId);
                List<CourseSection> list = result.getResult();
                list.forEach(CourseSection ->{
                    // 获取每一篇文章在redis中的浏览量，存入到数据库中
                    String key  = "id_"+CourseSection.getId();
                    Long view = redisUtil.size(key);
                    if(view>0){
                        Long views = view + CourseSection.getPlayTimes();
                        CourseSection.setPlayTimes(Math.toIntExact(views));
                    }
                });
                data.put("list",list);
                data.put("total",result.getPages());
                return new ObjectRestResponse<Object>().rel(true).data(data);
            }

//            //根据课程名获取课程的id
//            Integer CourseId = courseCatalogueBiz.getCourseId(courseName);
//            Example example = new Example(CourseSection.class);
//            example.createCriteria().andEqualTo("deleted",0).andEqualTo("couId",CourseId);
//            Page<Object> result = PageHelper.startPage(page, limit);
//            baseBiz.selectByExample(example);   //根据课程ID查找所有课时，分页
//            //用户开通这个课程下面的课时的开通记录
//            Example recordExample = new Example(FamilyWalletRecord.class);
//            recordExample.createCriteria().andEqualTo("userId",Integer.parseInt(userId)).andEqualTo("type",3).andEqualTo("courseId",CourseId);
//            List<FamilyWalletRecord> records = familyWalletRecordBiz.selectByExample(recordExample);
//
//            Map<String,Object> data = new HashMap<>();
//            data.put("rows",result.getResult());
//            data.put("total",result.getPages());
//            data.put("records",records);
//            return new ObjectRestResponse<Object>().rel(true).data(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }
    }

    /**
     * 用积分开通课时
     * @param userId
     * @param sectionId
     * @param detail
     * @return
     */
    @RequestMapping(value = "/payTheSection", method = RequestMethod.GET)
    @ResponseBody
    public Object payTheSection(String userId, String sectionId,
                                String detail, String couId,
                                String courseName, String sectionName){

            if (!userId.equals("undefined") && !sectionId.equals("undefined") && !detail.equals("undefined") && !couId.equals("undefined")) {
                FamilyUser user = familyUserBiz.selectById(Integer.parseInt(userId));
                if(user.getIntegral() < Integer.parseInt(detail)){    //积分少于开通需要的积分
                    return new ObjectRestResponse<>().rel(false);
                }else {
                    //扣除用户积分
                    FamilyUser userEntity = new FamilyUser();
                    userEntity.setId(Integer.parseInt(userId));
                    userEntity.setIntegral(user.getIntegral() - Integer.parseInt(detail));

                    //记录表插入记录
                    FamilyWalletRecord entity = new FamilyWalletRecord();
                    entity.setUserId(Integer.parseInt(userId));
                    entity.setMechaismId(Integer.parseInt(userId));
                    entity.setModifyTime(new Date());
                    entity.setType(3);
                    entity.setDetail(-Integer.parseInt(detail));
                    entity.setCourseSectionId(Integer.parseInt(sectionId));
                    entity.setCourseId(Integer.parseInt(couId));
                    entity.setRecordSn("兑换课程-" + courseName + "-" + sectionName);
                    entity.setLeftPoints(user.getIntegral() - Integer.parseInt(detail));

                    // 开启事务管理
                    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                    TransactionStatus status = txManager.getTransaction(def);
                    try {
                        familyUserBiz.updateSelectiveById(userEntity);
                        familyWalletRecordBiz.insert(entity);

                        txManager.commit(status);
                       return new ObjectRestResponse<>().rel(true);
                    }catch (Exception ex) {
                        txManager.rollback(status);
                        logger.error("网络连接超时", ex);
                        return new ObjectRestResponse<>().rel(true);
                    }
                }
            }else {
                return ResponseUtil.fail(40301, "错误！");
            }
        }

    /**
     * 根据id查询课时详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/getSectionById", method = RequestMethod.GET)
    @ResponseBody
    public Object list(Integer id){
        Example example = new Example(CourseSection.class);
        example.createCriteria().andEqualTo("id",id);
        List<CourseSection> list =  baseBiz.selectByExample(example);
       return new ObjectRestResponse<>().rel(true).data(list);
    }

}